﻿using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Linq;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.AspNetCore.Authorization;
using BuyWithoutLoseMoney;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
   /// <summary>
   /// 用户
   /// </summary>
    [Area("Admin")]
    public class UserController : BaseAdminController
    {
        private readonly IRepository<User, int> _userRepository;
        private readonly IRepository<UserAddress, int> _userAddressRepository;
        private readonly IRepository<UserType, int> _userTypeRepository;
       
        public UserController(IRepository<User, int> userRepository,
            IRepository<UserAddress, int> userAddressRepository, 
            IRepository<UserType, int> userTypeRepository, BuyWithoutLoseMoneyDBContext db) : base(db)
        {
            _userRepository = userRepository;
            _userAddressRepository = userAddressRepository;
            _userTypeRepository = userTypeRepository;
            
        }
        #region  用户列表，查询，新建，修改，删除
        /// <summary>
        /// 用户的列表展示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var Users = await _userRepository.GetAllListAsync();
            var Uadd = await _userAddressRepository.GetAllListAsync();
            var Utype = await _userTypeRepository.GetAllListAsync();
            ViewBag.Uadd = Uadd;
            ViewBag.Utype = Utype;
            return View(Users);
        }
        /// <summary>
        /// 根据用户名去查询
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Index(int page,int limit,string Name)
        {
            var users=await _userRepository.GetAllListAsync();
            var query = users.Where(x => true);
            if (!string.IsNullOrEmpty(Name))
            {
                query=query.Where(x=>x.NickName.Contains(Name));
            }
            var count=query.Count();
            var list = query.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit).ToList()
                .Select(x => new
                {
                    id = x.Id,
                    nickName = x.NickName,
                    gender = x.Gender,
                    phone = x.Phone,
                    email = x.EMail,
                    createtime = x.CreateTime.ToString(),
                    updatetime = x.UpdateTime.ToString(),
                    username = x.UserName,
                    iszhuxiao = x.IsZhuXiao,

                }); ;
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });
        }

        #endregion
    }
}
